<template>
  <span style="display: flex;flex-direction: row;align-items: baseline;">
    <el-cascader
      v-model="selectedVal"
      :placeholder="placeholder"
      style="width: 100%;"
      :options="options"
      :props="{value:'id',label:'name',multiple:multiple, checkStrictly: checkStrictly}"
      @change="handleChange" />
    <el-tooltip class="item" effect="dark" content="刷新分类" placement="bottom">
      <i v-if="refresh" class="el-icon-refresh common-cursor" style="margin-left: 5px;" @click="initData" />
    </el-tooltip>
  </span>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default() {
        return ''
      }
    },
    placeholder: {
      type: String,
      default() {
        return '请选择'
      }
    },
    type: { type: String, required: true },
    checkStrictly: { type: Boolean, default: true },
    multiple: {
      type: Boolean,
      default() {
        return false
      }
    },
    isShowAll: {
      type: Boolean,
      default() {
        return false
      }
    },
    refresh: {
      type: Boolean,
      default() {
        return true
      }
    }
  },
  data() {
    return {
      categoryType: this.type,
      selectedVal: [],
      options: []
    }
  },
  watch: {
    value: function(val) {
      if (val) {
        this.fetchCategoryFullInfo()
      }
      setTimeout(() => {
        // this.selectedVal = val
      }, 200)
    },
    selectedVal: function(val) {
      if (val.length > 0) {
        this.$emit('input', val[val.length - 1])
      }
    }
  },
  mounted() {
    this.initData()
  },
  created() {
    this.selectedVal = this.value
  },
  methods: {
    async initData() {
      try {
        const response = await this.$store.dispatch('upmsCategoryDictCacheTreeByType', this.type)
        let dataCategoryVos = []
        if (this.isShowAll) {
          dataCategoryVos.push({
            id: '-',
            name: '全部'
          })
          dataCategoryVos.push(...response)
        } else {
          dataCategoryVos = response
        }
        this.options = dataCategoryVos
      } catch (_) {
        console.log()
      }
    },
    fetchCategoryFullInfo() {
      if (this.value === '-') {
        return
      }
      if (this.checkStrictly === false) {
        return
      }
      this.$store.dispatch('upmsCategoryDictGetDetailsById', this.value).then(res => {
        this.selectedVal = res._fullCategoryIds
      })
    },
    handleChange() {
      this.$emit('change')
    },
    handleTabClick() {
      var datas = this.options.filter(item => {
        return item.dataDictItemCode === this.selectedVal
      })
      this.$emit('change', datas.length > 0 ? datas[0] : null)
    }
  }
}
</script>
<style lang="scss">
</style>
